package cn.edu.scau.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.scau.dao.CareMapper;
import cn.edu.scau.dao.CustomerMapper;
import cn.edu.scau.dao.NursingRecordMapper;
import cn.edu.scau.entity.Customer;
import cn.edu.scau.service.CustomerService;
import cn.edu.scau.service.LiveInRegisterService;

/**
 * 客户业务逻辑层接口实现类
 * @author LUSING
 *
 */
@Service
public class CustomerServiceImpl implements CustomerService{
	@Autowired
	private CustomerMapper customerMapper;
	@Autowired
	private LiveInRegisterService liveInRegisterService;
	
	@Autowired
	private CareMapper careMapper;
	
	@Override
	public List<Customer> selectAll() {
		List<Customer> customers = customerMapper.selectAll();
		return customers;
	}

	@Override
	public List<Customer> selectByNurseId(Integer nid) {
		List<Customer> customers = new ArrayList<Customer>();
		List<Integer> customerids = careMapper.selectByNurseId(nid);
		for(Integer cid : customerids) {
			customers.add(customerMapper.selectByPrimaryKey(cid));
		}
		return customers;
	}

	@Override
	public Customer selectByPrimaryKey(Integer cid) {
		Customer customers = customerMapper.selectByPrimaryKey(cid);
		return customers;
	}

	@Override
	public List<Customer> find(Integer cid, String cname) {
		List<Customer> customers = customerMapper.findByIdName(cid,cname);
		return customers;
	}

	@Override
	public boolean deleteCustomerByPrimaryKey(Integer cid) {
		int line = customerMapper.deleteByPrimaryKey(cid);
		return line>=1?  true : false;
	}

	@Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
	@Override
	public boolean safelyDeleteCustomer(Integer cid) {
		try {
			//修改customer
			Customer customer = customerMapper.selectByPrimaryKey(cid);
			customer.setCustomeruseflag(false);
			//修改入住记录
			//修改床位
			liveInRegisterService.updateFlag(cid);
			
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	@Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
	@Override
	public Integer insert(Customer record) {
		Integer id = null;
		if(1==customerMapper.insert(record)) {
			System.out.println("新增客户："+record);
			id =  record.getCustomerid();
		}
		else {
			System.out.println("新增用户失败");
		}
		return id;
	}
	
	
}
